package com.lcx.client;

import com.lcx.encoder.RpcDecoder;
import com.lcx.encoder.RpcEncoder;
import com.lcx.handler.UserServiceHandler;
import com.lcx.request.RpcRequest;
import com.lcx.serializer.JSONSerializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements IUserService {
    @Override
    public String sayHello(String msg) {
        System.out.println("request?"+msg);
        return "request?"+msg;
    }


    //创建一个启动服务器
    public static void startServer(String ip,int port) throws InterruptedException {
        //1、创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2、创建服务器启动引导类
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3、配置启动引导对象
        serverBootstrap.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class,new JSONSerializer()));
                        pipeline.addLast(new UserServiceHandler());
                    }
                });

        //4、绑定端口
        serverBootstrap.bind(ip,port).sync();
    }
}
